package com.yft.data.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.yft.data.service.InfoService;

@Controller
@RequestMapping("info")
public class InfoController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(InfoController.class);
	@Autowired
	private InfoService infoService;
	
	@RequestMapping(value = "typelist/{pageno}/{pagesize}", method = RequestMethod.GET)
	public @ResponseBody List<Map<String, Object>> getInfoTypeList(@PathVariable("pageno")int pageno, @PathVariable("pagesize")int pagesize){
		logger.info("url == info/fylist");
		return infoService.getInfoTypeList(pageno, pagesize);
	}
	//根据类型查询
	@RequestMapping(value = "list/{type}/{pageno}/{pagesize}", method = RequestMethod.GET)
	public @ResponseBody List<Map<String, Object>> getInfoListByType(@PathVariable("type")int type, @PathVariable("pageno")int pageno, @PathVariable("pagesize")int pagesize){
		logger.info("url == info/list");
		return infoService.getInfoListByType(type ,pageno, pagesize);
	}
	//新增食谱
	@RequestMapping(value = "savefood", method = RequestMethod.POST)
	public @ResponseBody int saveFood(
			@RequestParam("name") String name,
			@RequestParam("desc") String desc,
			@RequestParam("state") Integer state,
			@RequestParam("nid") Integer nid,
			HttpServletRequest request,HttpServletResponse response){
		logger.info("url == info/savefood");
		StringBuffer sb = new StringBuffer();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		String configPath = "/uploadImage";
		String ctxPath = request.getSession().getServletContext()
				.getRealPath("/")
				+ configPath;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		String ymd = sdf.format(new Date());
		ctxPath += ymd + "/";
		// 创建文件夹
		File file = new File(ctxPath);
		if (!file.exists()) {
			file.mkdirs();
		}
		String responseStr = "";
		String fileName = null;
		String newFileName = "";
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 上传文件名
			MultipartFile mf = entity.getValue();
			fileName = mf.getOriginalFilename();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
					.toLowerCase();

			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			newFileName = df.format(new Date()) + "_"
					+ new Random().nextInt(1000) + "." + fileExt;
			
			sb.append(configPath+ymd+"/"+newFileName+",");
			File uploadFile = new File(ctxPath + newFileName);
			try {
				FileCopyUtils.copy(mf.getBytes(), uploadFile);
			} catch (IOException e) {
				logger.info(e.toString());
			}
		}
		return infoService.saveFood(name, desc, state, nid, newFileName);
	}
	
	//食谱列表
	@RequestMapping(value = "foodlist/{pageno}/{pagesize}", method = RequestMethod.GET)
	public ModelAndView getFoodList(@PathVariable("pageno")int pageno, @PathVariable("pagesize")int pagesize){
		logger.info("url == info/list");
		ModelAndView ma = new ModelAndView();
		List<Map<String, Object>> maplist = infoService.getFoodList(pageno, pagesize);
		// 返回的view名称
		ma.addObject("maplist", maplist);
		ma.addObject("pageno", pageno);
		ma.addObject("pagesize", pagesize);
		ma.setViewName("food/getlist");
		return ma;
	}
	
	//得到食谱对象
	@RequestMapping(value = "getfood/{id}", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getFoodByID(@PathVariable("id")int id){
		logger.info("url == food/"+id);
		Map<String, Object> map = infoService.getFoodByID(id);
		return map;
	}
	
	//删除食谱
	@RequestMapping(value = "deletefood/{id}", method = RequestMethod.GET)
	public @ResponseBody int deleteFoodByID(@PathVariable("id")int id){
		logger.info("url == info/list");
		int i = infoService.deleteFoodByID(id);
		return i;
	}
	
	//修改食谱
	@RequestMapping(value = "updatefood", method = RequestMethod.POST)
	public @ResponseBody int updatefood(
			@RequestParam("id") Integer id,
			@RequestParam("name") String name,
			@RequestParam("desc") String desc,
			@RequestParam("state") Integer state,
			@RequestParam("nid") Integer nid,
			HttpServletRequest request,HttpServletResponse response){
		logger.info("url == info/updatefood");
		StringBuffer sb = new StringBuffer();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		String configPath = "/uploadImage";
		String ctxPath = request.getSession().getServletContext()
				.getRealPath("/")
				+ configPath;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		String ymd = sdf.format(new Date());
		ctxPath += ymd + "/";
		// 创建文件夹
		File file = new File(ctxPath);
		if (!file.exists()) {
			file.mkdirs();
		}
		String responseStr = "";
		String fileName = null;
		String newFileName = "";
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 上传文件名
			MultipartFile mf = entity.getValue();
			fileName = mf.getOriginalFilename();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
					.toLowerCase();

			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			newFileName = df.format(new Date()) + "_"
					+ new Random().nextInt(1000) + "." + fileExt;
			
			sb.append(configPath+ymd+"/"+newFileName+",");
			File uploadFile = new File(ctxPath + newFileName);
			try {
				FileCopyUtils.copy(mf.getBytes(), uploadFile);
			} catch (IOException e) {
				logger.info(e.toString());
			}
		}
		return infoService.updateFood(id, name, desc, state, nid, newFileName);
	}
	
	//发布通知
	@RequestMapping(value = "savenotice", method = RequestMethod.POST)
	public @ResponseBody int saveNotice(
			@RequestParam("title") String title,
			@RequestParam("content") String content,@RequestParam("state") Integer state,@RequestParam("classid") Integer classid){
		logger.info("url == info/savenotice");
		return infoService.saveNotice(title, content, state, classid);
	}
	
	//通知列表
	@RequestMapping(value = "noticelist/{pageno}/{pagesize}", method = RequestMethod.GET)
	public @ResponseBody List<Map<String, Object>> getNoticeList(@PathVariable("pageno")int pageno, @PathVariable("pagesize")int pagesize){
		logger.info("url == notice/list");
		List<Map<String, Object>> maplist = infoService.getNoticeList(pageno, pagesize);
		// 返回的view名称
		return maplist;
	}
	
	//得到通知对象
	@RequestMapping(value = "getnotice/{id}", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getNoticeByID(@PathVariable("id")int id){
		logger.info("url == getnotice/"+id);
		Map<String, Object> map = infoService.getNoticeByID(id);
		return map;
	}
	
	//删除通知
	@RequestMapping(value = "deletenotice/{id}", method = RequestMethod.GET)
	public @ResponseBody int deleteNoticeByID(@PathVariable("id")int id){
		logger.info("url == deletenotice/list");
		int i = infoService.deleteNoticeByID(id);
		return i;
	}
	
	//修改通知
	@RequestMapping(value = "updatenotice", method = RequestMethod.POST)
	public @ResponseBody int updateNotice(
			@RequestParam("id") Integer id,
			@RequestParam("title") String title,
			@RequestParam("content") String content,@RequestParam("state") Integer state,@RequestParam("classid") Integer classid){
		logger.info("url == info/updatenotice");
		return infoService.updateNotice(id, title, content, state, classid);
	}
	//发布活动活动
	@RequestMapping(value = "saveactive", method = RequestMethod.POST)
	public @ResponseBody int saveActive(
			@RequestParam("cid") Integer cid,
			@RequestParam("start") String start,
			@RequestParam("end") String end,
			@RequestParam("address") String address,
			@RequestParam("content") String content){
		logger.info("url == info/saveactive");
		return infoService.saveActive(cid,start,end,address,content);
	}
	
	//活动列表
	@RequestMapping(value = "activelist/{pageno}/{pagesize}", method = RequestMethod.GET)
	public  @ResponseBody List<Map<String, Object>> getActiveList(@PathVariable("pageno")int pageno, @PathVariable("pagesize")int pagesize){
		logger.info("url == active/list");
		List<Map<String, Object>> maplist = infoService.getActiveList(pageno, pagesize);
		return maplist;
	}
	
	//得到活动对象
	@RequestMapping(value = "getactive/{id}", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getActiveByID(@PathVariable("id")int id){
		logger.info("url == getactive/"+id);
		Map<String, Object> map = infoService.getActiveByID(id);
		return map;
	}
	
	//删除活动
	@RequestMapping(value = "deleteactive/{id}", method = RequestMethod.GET)
	public @ResponseBody int deleteActiveByID(@PathVariable("id")int id){
		logger.info("url == deleteactive/"+id);
		int i = infoService.deleteActiveByID(id);
		return i;
	}
	
	//修改活动
	@RequestMapping(value = "updateactive", method = RequestMethod.POST)
	public @ResponseBody int updateActive(
			@RequestParam("id") Integer id,
			@RequestParam("cid") Integer cid,
			@RequestParam("start") String start,
			@RequestParam("end") String end,
			@RequestParam("address") String address,
			@RequestParam("content") String content){
		logger.info("url == info/saveactive");
		return infoService.updateActive(id,cid,start,end,address,content);
	}
	//发布亲子作业
	@RequestMapping(value = "saveparentingwork", method = RequestMethod.POST)
	public @ResponseBody int saveParentingWork(
			@RequestParam("cid") Integer cid,
			@RequestParam("title") String title,
			@RequestParam("content") String content){
		logger.info("url == info/saveparentingwork");
		return infoService.saveParentingWork(cid,title,content);
	}
	
	//亲子作业列表
	@RequestMapping(value = "pwlist/{pageno}/{pagesize}", method = RequestMethod.GET)
	public  @ResponseBody List<Map<String, Object>> getParentingWorkList(@PathVariable("pageno")int pageno, @PathVariable("pagesize")int pagesize){
		logger.info("url == info/list");
		List<Map<String, Object>> maplist = infoService.getParentingWorkList(pageno, pagesize);
		// 返回的view名称
		return maplist;
	}
	
	//亲子作业对象
	@RequestMapping(value = "pw/{id}", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getParentingWorkByID(@PathVariable("id")int id){
		logger.info("url == info/list");
		Map<String, Object> map = infoService.getParentingWorkByID(id);
		return map;
	}
	//亲子作业对象
	@RequestMapping(value = "deletepw/{id}", method = RequestMethod.GET)
	public @ResponseBody int deleteParentingWorkByID(@PathVariable("id")int id){
		logger.info("url == info/list");
		int i = infoService.deleteParentingWorkByID(id);
		return i;
	}
	//发布亲子作业
	@RequestMapping(value = "updateparentingwork", method = RequestMethod.POST)
	public @ResponseBody int updateParentingWork(
			@RequestParam("id") Integer id,
			@RequestParam("cid") Integer cid,
			@RequestParam("title") String title,
			@RequestParam("content") String content){
		logger.info("url == info/saveparentingwork");
		return infoService.updateParentingWork(id,cid,title,content);
	}
	//发布温馨提示
	@RequestMapping(value = "saveremind", method = RequestMethod.POST)
	public @ResponseBody int saveRemind(
			@RequestParam("nid") Integer nid,
			@RequestParam("content") String content){
		logger.info("url == info/saveremind");
		return infoService.saveRemind(nid,content);
	}
	
	//温馨提示列表
	@RequestMapping(value = "remindlist/{pageno}/{pagesize}", method = RequestMethod.GET)
	public  @ResponseBody List<Map<String, Object>> getRemindList(@PathVariable("pageno")int pageno, @PathVariable("pagesize")int pagesize){
		logger.info("url == info/list");
		List<Map<String, Object>> maplist = infoService.getRemindList(pageno, pagesize);
		return maplist;
	}
	
	//温馨提示对象
	@RequestMapping(value = "getremind/{id}", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getRemindByID(@PathVariable("id")int id){
		logger.info("url == info/getremind"+id);
		Map<String, Object> map = infoService.getRemindByID(id);
		return map;
	}
	
	//删除温馨提示对象
	@RequestMapping(value = "deleteremind/{id}", method = RequestMethod.GET)
	public @ResponseBody int deleteRemindByID(@PathVariable("id")int id){
		logger.info("url == info/deleteremind"+id);
		int i = infoService.deleteRemindByID(id);
		return i;
	}
	//update温馨提示
	@RequestMapping(value = "updateremind", method = RequestMethod.POST)
	public @ResponseBody int updateRemind(
			@RequestParam("id") Integer id,
			@RequestParam("nid") Integer nid,
			@RequestParam("content") String content){
		logger.info("url == info/saveremind");
		return infoService.updateRemind(id,nid,content);
	}
	//保存排课信息
	@RequestMapping(value = "saveWeekCourse", method = RequestMethod.POST)
	public @ResponseBody int saveWeekCourse(
			@RequestParam("nid") Integer nid,
			@RequestParam("cid") Integer cid,
			@RequestParam("daysr") Integer daysr,
			@RequestParam("weekNo") Integer weekNo,
			@RequestParam("courseid") Integer courseid,
			@RequestParam("courseName") String courseName){
		logger.info("url == info/saveWeekCourse");
		return infoService.saveWeekCourse(nid,cid,daysr,weekNo,courseid,courseName);
	}
	
	//查询排课信息
	@RequestMapping(value = "wclist/{pageno}/{pagesize}/{cid}", method = RequestMethod.GET)
	public @ResponseBody List<Map<String, Object>> getWeekCourseListByClassID(@PathVariable("pageno")int pageno, @PathVariable("pagesize")int pagesize, @PathVariable("cid")int cid){
		logger.info("url == info/wclist");
		return infoService.getWeekCourseList(pageno, pagesize,cid);
	}
	
	//查询课程信息
	@RequestMapping(value = "courselist/{pageno}/{pagesize}/{cid}", method = RequestMethod.GET)
	public @ResponseBody List<Map<String, Object>> getCourseListByClassID(@PathVariable("pageno")int pageno, @PathVariable("pagesize")int pagesize, @PathVariable("cid")int cid){
		logger.info("url == info/courselist");
		return infoService.getCourseList(pageno, pagesize,cid);
	}
	
	//保存排课信息
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "saveCourse", method = RequestMethod.POST)
	public @ResponseBody int saveCourse(
			@RequestParam("nid") Integer nid,
			@RequestParam("cid") Integer cid,
			@RequestParam("isThisWeek") Integer isThisWeek,
			@RequestParam("courses") String courses){
		logger.info("url == info/saveCourse");
		//解析
		//[{"lesson":"1","week":"1","name":"语文"},{"lesson":"1","week":"2","name":"数学"},{"lesson":"1","week":"3","name":"音乐"},{"lesson":"1","week":"4","name":"英语"},{"lesson":"1","week":"5","name":"体育"},{"lesson":"2","week":"1","name":"语文"},{"lesson":"2","week":"2","name":"数学"},{"lesson":"2","week":"3","name":"音乐"},{"lesson":"2","week":"4","name":"英语"},{"lesson":"2","week":"5","name":"体育"},{"lesson":"3","week":"1","name":"语文"},{"lesson":"3","week":"2","name":"数学"},{"lesson":"3","week":"3","name":"音乐"},{"lesson":"3","week":"4","name":"英语"},{"lesson":"3","week":"5","name":"体育"},{"lesson":"4","week":"1","name":"语文"},{"lesson":"4","week":"2","name":"数学"},{"lesson":"4","week":"3","name":"音乐"},{"lesson":"4","week":"4","name":"英语"},{"lesson":"4","week":"5","name":"体育"}]
		System.out.println(" nid == "+ nid + ";" + " cid == "+ nid + ";" + " isThisWeek == "+ nid + ";");
//		String json = "[{\"lesson\":\"1\",\"week\":\"1\",\"name\":\"语文\"},{\"lesson\":\"1\",\"week\":\"2\",\"name\":\"数学\"},{\"lesson\":\"1\",\"week\":\"3\",\"name\":\"音乐\"},{\"lesson\":\"1\",\"week\":\"4\",\"name\":\"英语\"},{\"lesson\":\"1\",\"week\":\"5\",\"name\":\"体育\"},{\"lesson\":\"2\",\"week\":\"1\",\"name\":\"语文\"},{\"lesson\":\"2\",\"week\":\"2\",\"name\":\"数学\"},{\"lesson\":\"2\",\"week\":\"3\",\"name\":\"音乐\"},{\"lesson\":\"2\",\"week\":\"4\",\"name\":\"英语\"},{\"lesson\":\"2\",\"week\":\"5\",\"name\":\"体育\"},{\"lesson\":\"3\",\"week\":\"1\",\"name\":\"语文\"},{\"lesson\":\"3\",\"week\":\"2\",\"name\":\"数学\"},{\"lesson\":\"3\",\"week\":\"3\",\"name\":\"音乐\"},{\"lesson\":\"3\",\"week\":\"4\",\"name\":\"英语\"},{\"lesson\":\"3\",\"week\":\"5\",\"name\":\"体育\"},{\"lesson\":\"4\",\"week\":\"1\",\"name\":\"语文\"},{\"lesson\":\"4\",\"week\":\"2\",\"name\":\"数学\"},{\"lesson\":\"4\",\"week\":\"3\",\"name\":\"音乐\"},{\"lesson\":\"4\",\"week\":\"4\",\"name\":\"英语\"},{\"lesson\":\"4\",\"week\":\"5\",\"name\":\"体育\"}]";
		String json = courses;
		ObjectMapper objectMapper = new ObjectMapper();
		List<LinkedHashMap<String, Object>> list = null;
		try {
		    list = objectMapper.readValue(json, List.class);
		    System.out.println(list.size());
		    for (int i = 0; i < list.size(); i++) {
		        Map<String, Object> map = list.get(i);
		        Set<String> set = map.keySet();
		        for (Iterator<String> it = set.iterator();it.hasNext();) {
		            String key = it.next();
		            System.out.println(key + ":" + map.get(key));
		        }
		    }
		} catch (JsonParseException e) {
		    e.printStackTrace();
		} catch (JsonMappingException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
		
		return infoService.saveCourse(nid, cid, isThisWeek, list);
//		return 0;
	}
	//查询排课信息
	@RequestMapping(value = "getCourselist", method = RequestMethod.GET)
	public @ResponseBody List<Map<String, Object>> getWeekCourselistByOtherID(
			@RequestParam("nid") Integer nid,
			@RequestParam("cid") Integer cid){
		logger.info("url == info/courselistCourse");
		
		return infoService.getWeekCourselistByOtherID(nid, cid);
	}
}
